package moddbbackendrevisited.resource;

import java.sql.*;
import moddbbackendrevisited.schema.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;
import moddbbackendrevisited.Main;

@Path("/tables/{id}/rows")
public class RowsResource {

  @Context
  protected UriInfo uriInfo;

  /*
   * List All Rows in a Table
   * http://code.google.com/p/moddb08/wiki/BackendInterfaceVersionOne#List_All_Rows_in_a_Table
   */
  @GET
  @Produces("application/xml")
  public Response get(@PathParam("id") String tableName) {

    Statement stmnt;
    
    // Create statement from current database connection, return SERVICE UNAVAILABLE
    // on error
    try {
      stmnt = Main.dbCon.createStatement();
    } catch (SQLException e) {
      return Response.status(Status.SERVICE_UNAVAILABLE).build();
    }

    try {
      // Select all row ids from chosen table
      ResultSet rs = stmnt.executeQuery("SELECT \"id;text/plain\" from " + tableName);

      // Build Rows schema
      Rows rows = new Rows();

      while (rs.next()) {
        rows.add(new Row(rs.getInt(1)));
      }

      rs.close();

      return Response.ok(rows).build();

    } catch (SQLException e) {
      e.printStackTrace();
      // 404 on error (probably due to table not found)
      return Response.status(Status.NOT_FOUND).build();
    }
	}

  /*
   * Add a Row to a Table
   * http://code.google.com/p/moddb08/wiki/BackendInterfaceVersionOne#Add_a_Row_to_a_Table
   */
  @POST
	//@Consumes('application/xml')
  public Response post(@PathParam("id") String tableName) {

    Statement stmnt;

    // Create statement from current database connection, return SERVICE UNAVAILABLE
    // on error
    try {
      stmnt = Main.dbCon.createStatement();
    } catch (SQLException e) {
      return Response.status(Status.SERVICE_UNAVAILABLE).build();
    }

    try {
      // Insert empty row into chosen table
      stmnt.executeUpdate("INSERT INTO " + tableName + " (\"id;text/plain\") values (NULL)");
      // Get new row id, if any
      ResultSet rs = stmnt.getGeneratedKeys();

      try {
        if (rs.next()) {
            // Created and location
            return Response.created(uriInfo.getAbsolutePath().resolve("/tables/" + tableName + "/rows/" + rs.getInt(1))).build();
        } else {
            // Row was not inserted
            return Response.status(Status.BAD_REQUEST).build();
        }
      } finally {
        rs.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
      return Response.status(Status.NOT_FOUND).build();
    }

  }

  /*
   * Delete a Row from a Table
   * http://code.google.com/p/moddb08/wiki/BackendInterfaceVersionOne#Delete_a_Row_from_a_Table
   */
  @Path("/{rowId}")
  @DELETE
  public Response delete(@PathParam("id") String tableName,
                         @PathParam("rowId") int rowId) {

    Statement stmnt;
    
    // Create statement from current database connection, return SERVICE UNAVAILABLE
    // on error
    try {
      stmnt = Main.dbCon.createStatement();
    } catch (SQLException e) {
      return Response.status(Status.SERVICE_UNAVAILABLE).build();
    }

    try {
      // Delete chosen row from chosen table
      stmnt.executeUpdate("DELETE FROM " + tableName + " WHERE \"id;text/plain\" = " + rowId);
      return Response.status(Status.NO_CONTENT).build();
    } catch (SQLException e) {
      e.printStackTrace();
      return Response.status(Status.NOT_FOUND).build();
    }
  }

}
